package game

import "fmt"

type Board struct {
	X         int
	Y         int
	AllFlower [][]Flower
}

func (b *Board) PrintBoard() {
	yMax := len(b.AllFlower) - 1
	for y := yMax; y >= 0; y-- {
		fmt.Println(b.AllFlower[y])
	}
}

// InitBoard 初始化棋盘大小
func InitBoard(xMax, yMax int) Board {
	// 二维数组
	temp := make([][]Flower, yMax)
	for i := 0; i < yMax; i++ {
		xInts := make([]Flower, xMax)
		temp[i] = xInts
	}
	board := Board{X: xMax, Y: yMax, AllFlower: temp}
	return board
}
func (b *Board) GetFlower(targetX, targetY int) *Flower {
	if b.X < targetX+1 || targetX < 0 {
		return nil
	}
	if b.Y < targetY+1 || targetY < 0 {
		return nil
	}
	return &b.AllFlower[targetX][targetY]
}

// 以左下为原点
func (b *Board) AddFlower(flower Flower, X, Y int) bool {
	if X < 0 || Y > b.X {
		return false
	}
	if X < 0 || Y > b.Y {
		return false
	}

	b.AllFlower[Y][X] = flower
	b.CheckTakeAway(Y, X)
	return true
}

func (b *Board) RemFlower(targetX, targetY int) {
	flower := b.GetFlower(targetX, targetY)
	if flower == nil {
		return
	}
	flower.Remove()
}

type WaitingXY struct {
	x int
	y int
}

func (b *Board) CheckTakeAway(x, y int) []WaitingXY {
	temp := make([]WaitingXY, 0)

	flower := b.GetFlower(x, y)
	if flower == nil || len(flower.Colour) < 1 {
		return temp
	}
	targetColour := b.GetFlower(x, y).Colour[0]
	// 检查上下左右 四个坐标
	x1 := x - 1
	x2 := x + 1
	if b.CheckColour(targetColour, x1, y) && b.CheckColour(targetColour, x1-1, y) {
		temp = append(temp, WaitingXY{x: x1, y: y})
		temp = append(temp, WaitingXY{x: x1 - 1, y: y})
	}
	if b.CheckColour(targetColour, x2, y) && b.CheckColour(targetColour, x2+1, y) {
		temp = append(temp, WaitingXY{x: x2, y: y})
		temp = append(temp, WaitingXY{x: x2 + 1, y: y})
	}

	y1 := y - 1
	y2 := y + 1
	if b.CheckColour(targetColour, x, y1) && b.CheckColour(targetColour, x, y1-1) {
		temp = append(temp, WaitingXY{x: x, y: y1})
		temp = append(temp, WaitingXY{x: x, y: y1 - 1})
	}
	if b.CheckColour(targetColour, x, y2) && b.CheckColour(targetColour, x, y2+1) {
		temp = append(temp, WaitingXY{x: x, y: y2})
		temp = append(temp, WaitingXY{x: x, y: y2 + 1})
	}

	if len(temp) > 0 {
		temp = append(temp, WaitingXY{x: x, y: y})
		for _, waitingXY := range temp {
			b.RemFlower(waitingXY.x, waitingXY.y)
			b.CheckTakeAway(x, y)
		}

	}

	return temp
}

func (b *Board) CheckColour(targetColour, x, y int) bool {
	flower := b.GetFlower(x, y)
	if flower != nil && len(flower.Colour) > 0 {
		return flower.Colour[0] == targetColour
	}
	return false
}
